package com.zyh.flink.day01;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
//注意Tuple2一定要导入flink包下的类，而非scala包下的类
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

public class FlinkWordCountJobWithAnonymous {
    public static void main(String[] args) throws Exception {
        //1.获取运行环境
        StreamExecutionEnvironment environment = StreamExecutionEnvironment.getExecutionEnvironment();

        //2.创建DataStream：监听hadoop10机器
        DataStreamSource<String> dataStream = environment.socketTextStream("hadoop10", 9999);

        //3.使用算子对流上的数据进行转换：
        SingleOutputStreamOperator<Tuple2<String, Integer>> result = dataStream.flatMap(new FlatMapFunction<String, String>() {
            @Override
            //根据空格拆分后输出
            public void flatMap(String value, Collector<String> out) throws Exception {
                String[] words = value.split("\\s+");
                for (String word : words) {
                    out.collect(word);
                }
            }
        }).map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            //将单词映射为(单词,1)
            public Tuple2<String, Integer> map(String value) throws Exception {
                return Tuple2.of(value, 1);
            }
        }).keyBy(0)//根据单词分组 0表示tuple中元素的下标，此处表示单词
                .sum(1);//对各组单词次数进行汇总，1表示tuple元素下标，此处即单词个数1

        //4.通过print这个sink算子输出结果到控制台
        result.print();

        //5.发布执行流计算任务
        environment.execute("flinkWordCountJob");
    }
}